import axios from 'axios'
import configManager from './config'

// 创建axios实例
const api = axios.create({
  baseURL: '/api',
  timeout: 3000000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
api.interceptors.request.use(
  config => {
    // 如果是氧屋平台的请求，添加Authorization头
    const platformConfig = configManager.getPlatformConfig()
    if (config.isPlatformRequest && platformConfig.authorization) {
      config.headers['Authorization'] = platformConfig.authorization
    }
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  response => {
    return response.data
  },
  error => {
    const message = error.response?.data?.message || error.message || '请求失败'
    return Promise.reject(new Error(message))
  }
)

export default {
  // 执行SQL查询
  executeQuery(sql, dbConfig) {
    return api.post('/sql/query', {
      sql,
      dbConfig: {
        host: dbConfig.host,
        port: dbConfig.port,
        username: dbConfig.username,
        password: dbConfig.password,
        database: dbConfig.database
      }
    })
  },
  
  // 测试数据库连接
  testConnection(dbConfig) {
    return api.post('/sql/test-connection', {
      dbConfig: {
        host: dbConfig.host,
        port: dbConfig.port,
        username: dbConfig.username,
        password: dbConfig.password,
        database: dbConfig.database
      }
    })
  },
  
  // AI分析SQL执行计划
  analyzeExecutionPlan(sql, dbConfig) {
    return api.post('/ai/analyze', {
      sql,
      dbConfig: {
        host: dbConfig.host,
        port: dbConfig.port,
        username: dbConfig.username,
        password: dbConfig.password,
        database: dbConfig.database
      }
    })
  },
  
  // 获取表注释信息
  getTableComments(tableNames, dbConfig) {
    return api.post('/sql/table-comments', {
      tableNames,
      dbConfig: {
        host: dbConfig.host,
        port: dbConfig.port,
        username: dbConfig.username,
        password: dbConfig.password,
        database: dbConfig.database
      }
    })
  },
  
  // 生成ER图
  generateErDiagram(erData, dbConfig) {
    return api.post('/ai/er-diagram', {
      erData,
      dbConfig: {
        host: dbConfig.host,
        port: dbConfig.port,
        username: dbConfig.username,
        password: dbConfig.password,
        database: dbConfig.database
      }
    })
  }
}

// 氧屋平台API（单独的axios实例）
export const platformApi = {
  // 创建平台请求实例
  createRequest() {
    const platformConfig = configManager.getPlatformConfig()
    if (!platformConfig.baseUrl) {
      throw new Error('请先配置氧屋平台URL')
    }
    
    return axios.create({
      baseURL: platformConfig.baseUrl,
      timeout: 3000000,
      headers: {
        'Content-Type': 'application/json',
        'Authorization': platformConfig.authorization || ''
      }
    })
  },
  
  // 示例：调用平台接口
  async callPlatformApi(endpoint, data) {
    try {
      const instance = this.createRequest()
      const response = await instance.post(endpoint, data)
      return response.data
    } catch (error) {
      throw new Error(error.response?.data?.message || error.message)
    }
  },
  
  // 获取数据字典列表
  async getDictDataByType(dictType) {
    try {
      const platformConfig = configManager.getPlatformConfig()
      if (!platformConfig.baseUrl) {
        throw new Error('请先配置氧屋平台URL')
      }
      
      // 创建专门用于表单数据的axios实例
      const instance = axios.create({
        baseURL: platformConfig.baseUrl,
        timeout: 3000000,
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
          'Authorization': platformConfig.authorization || ''
        }
      })
      
      // 将数据转换为URLSearchParams格式
      const params = new URLSearchParams()
      params.append('type', dictType)
      
      const response = await instance.post('/api/dictdata/listByType', params)
      
      // 检查响应结构
      if (response.data && response.data.success && response.data.data && response.data.data.result) {
        // 按code字段升序排序
        const sortedData = response.data.data.result.sort((a, b) => {
          return String(a.code).localeCompare(String(b.code))
        })
        
        return {
          success: true,
          data: {
            result: sortedData,
            dictType: dictType
          }
        }
      } else {
        throw new Error('返回数据格式不正确')
      }
    } catch (error) {
      throw new Error(error.response?.data?.message || error.message)
    }
  },
  
  // 获取枚举数据列表
  async getEnumDataByNames(enumNames) {
    try {
      const platformConfig = configManager.getPlatformConfig()
      if (!platformConfig.baseUrl) {
        throw new Error('请先配置氧屋平台URL')
      }
      
      // 创建专门用于表单数据的axios实例
      const instance = axios.create({
        baseURL: platformConfig.baseUrl,
        timeout: 3000000,
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',
          'Authorization': platformConfig.authorization || ''
        }
      })
      
      // 将枚举名数组转换为JSON格式的URLSearchParams
      const params = new URLSearchParams()
      params.append('enumNameJson', JSON.stringify(enumNames))
      
      const response = await instance.post('/api/common/enum/v1/enumListMap', params)
      
      // 检查响应结构
      if (response.data && response.data.success && response.data.data && response.data.data.result) {
        const result = response.data.data.result
        
        // 如果只查询一个枚举，返回该枚举的数据
        if (enumNames.length === 1) {
          const enumName = enumNames[0]
          const enumData = result[enumName]
          
          if (enumData && Array.isArray(enumData)) {
            // 按value字段升序排序
            const sortedData = enumData.sort((a, b) => {
              return Number(a.value) - Number(b.value)
            })
            
            return {
              success: true,
              data: {
                result: sortedData,
                enumName: enumName
              }
            }
          } else {
            throw new Error(`枚举 ${enumName} 数据不存在或格式错误`)
          }
        } else {
          // 多个枚举的情况，返回所有数据
          const processedResult = {}
          for (const enumName of enumNames) {
            if (result[enumName] && Array.isArray(result[enumName])) {
              processedResult[enumName] = result[enumName].sort((a, b) => {
                return Number(a.value) - Number(b.value)
              })
            }
          }
          
          return {
            success: true,
            data: {
              result: processedResult
            }
          }
        }
      } else {
        throw new Error('返回数据格式不正确')
      }
    } catch (error) {
      throw new Error(error.response?.data?.message || error.message)
    }
  }
}